package com.zkthink.ceres.applet.pcVehicles.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.zkthink.base.R;
import com.zkthink.ceres.applet.ceresStore.domain.vo.NearbyIdLocalVo;
import com.zkthink.ceres.applet.product.domain.entity.AppletProduct;
import com.zkthink.ceres.applet.product.mapper.AppletProductMapper;
import com.zkthink.ceres.applet.server.domain.entity.AppletServer;
import com.zkthink.ceres.applet.server.mapper.AppletServerMapper;
import com.zkthink.ceres.common.utils.GaoDeMapUtil;
import com.zkthink.ceres.applet.order.domain.entity.AppletProductOrder;
import com.zkthink.ceres.applet.order.domain.entity.AppletServerOrder;
import com.zkthink.ceres.applet.order.mapper.AppletProductOrderMapper;
import com.zkthink.ceres.applet.order.mapper.AppletServerOrderMapper;
import com.zkthink.ceres.applet.pcVehicles.domain.vo.PcVehiclesServerVo;
import com.zkthink.ceres.member.dao.MemberAddressMapper;
import com.zkthink.ceres.member.entity.MemberAddress;
import com.zkthink.ceres.store.dto.ApplyVehiclesDto;
import com.zkthink.ceres.store.dto.VehiclesServerRegionDto;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zkthink.ceres.applet.pcVehicles.mapper.PcVehiclesMapper;
import com.zkthink.ceres.applet.pcVehicles.domain.entity.PcVehicles;
import com.zkthink.ceres.applet.pcVehicles.service.PcVehiclesService;

import static com.zkthink.ceres.applet.authority.config.AuthorityWebConfiguration.getMid;

/**
 * @Author cmz
 * @Date 2024-05-06 9:16
 */
@Service
public class PcVehiclesServiceImpl extends ServiceImpl<PcVehiclesMapper, PcVehicles> implements PcVehiclesService {

    @Resource
    private PcVehiclesMapper pcVehiclesMapper;

    @Resource
    private AppletServerOrderMapper appletServerOrderMapper;

    @Resource
    private AppletProductOrderMapper appletProductOrderMapper;

    @Resource
    private MemberAddressMapper memberAddressMapper;
    @Resource
    private AppletServerMapper appletServerMapper;
    @Resource
    private AppletProductMapper appletProductMapper;

    @Override
    public R findNearbyStore(NearbyIdLocalVo nearbyIdLocalVo) {
        //查询可接这个服务的所有营业中的理疗车
        List<PcVehiclesServerVo> list = new ArrayList<>();
        Long addressId = nearbyIdLocalVo.getAddressId();
//        if (nearbyIdLocalVo.getOrderType() == 0) {
//            //服务订单
//            AppletServer server = appletServerMapper.selectById(nearbyIdLocalVo.getServerId());
//            list = pcVehiclesMapper.selectByServerIdAndPrice(server.getId(), server.getStorePrice());
//
//        } else if (nearbyIdLocalVo.getOrderType() == 1) {
//            //产品订单
//            AppletProduct product = appletProductMapper.selectById(nearbyIdLocalVo.getServerId());
//            //找到了订单信息，根据订单信息中的产品id和价格去检索对应的相关车辆
//            list = pcVehiclesMapper.selectByProductIdAndPrice(product.getId(), product.getStorePrice());
//
//        }
        QueryWrapper<PcVehicles> objectQueryWrapper = new QueryWrapper<>();
        objectQueryWrapper.eq("vehicles_state",1);
        objectQueryWrapper.eq("apply_type",1);
        list = pcVehiclesMapper.selectList(objectQueryWrapper).stream().map(a -> {
            PcVehiclesServerVo pcVehiclesServerVo = new PcVehiclesServerVo();
            BeanUtils.copyProperties(a, pcVehiclesServerVo);
            return pcVehiclesServerVo;
        }).collect(Collectors.toList());
        if (addressId != null) {
            //订单获取对应的地址信息
            MemberAddress memberAddress = memberAddressMapper.selectById(addressId);
            //根据地址信息获取收货经纬度
            String address = memberAddress.getProvince() + memberAddress.getCity() + memberAddress.getArea() + memberAddress.getAddress();
            String s = GaoDeMapUtil.httpURLConectionGET(address, "");
            String[] split = s.split(",");
            //更新传入的经纬度信息，更改为根据收货地址获取理疗车信息
            nearbyIdLocalVo.setLongitude(split[0]);
            nearbyIdLocalVo.setLatitude(split[1]);
        }

        for (PcVehiclesServerVo pcVehicles : list) {
            if (pcVehicles.getLatitude() != null && pcVehicles.getLongitude() != null) {
                //根据经纬度查询距离
                Double distance = GaoDeMapUtil.getDistance(Double.valueOf(pcVehicles.getLatitude()), Double.valueOf(pcVehicles.getLongitude()), Double.valueOf(nearbyIdLocalVo.getLatitude()), Double.valueOf(nearbyIdLocalVo.getLongitude()));
                pcVehicles.setDistance(distance);
            }else {
                pcVehicles.setDistance(0.00);
            }
        }
        //筛选出在服务范围内的理疗车
        //1.理疗车没有开启服务范围(默认接所有位置的订单)
        //2.理疗车开启了服务范围，服务范围大于理疗车当前位置到服务位置的距离
        list = list.stream().filter(a -> a.getIsOpenRadius() == null || a.getIsOpenRadius() == 1 || (a.getServiceRadius() * 1000) > a.getDistance()).collect(Collectors.toList());
        list.sort((a, b) -> (int) (a.getDistance() - b.getDistance()));//将距离从小到大排序
        return R.success(list);
    }

    @Override
    public R applyVehicles(ApplyVehiclesDto applyVehiclesDto) {
        Long mid = getMid();
        QueryWrapper<PcVehicles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", mid);
        PcVehicles pcVehicles = pcVehiclesMapper.selectOne(queryWrapper);
        if (pcVehicles == null) {
            pcVehicles = new PcVehicles();
            BeanUtils.copyProperties(applyVehiclesDto, pcVehicles);
            pcVehicles.setIdImgs(String.join(",", applyVehiclesDto.getIdImgList()));
            pcVehicles.setVehiclePhoto(String.join(",", applyVehiclesDto.getVehiclePhotoList()));
            pcVehicles.setCreateUser(mid);
            pcVehicles.setCreateTime(new Date());
            pcVehicles.setUserId(mid);
            pcVehicles.setCommission(0.0);
            int i = pcVehiclesMapper.insert(pcVehicles);

            return i > 0 ? R.success() : R.fail("添加失败");
        } else {
            return R.fail("已有理疗车，无法申请");
        }
    }

    @Override
    public R findVehicles(Long userid) {
        QueryWrapper<PcVehicles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userid);
        PcVehicles pcVehicles = pcVehiclesMapper.selectOne(queryWrapper);
        Map<String, Object> map = new HashMap<>();
        if (pcVehicles != null) {
            ApplyVehiclesDto dto = new ApplyVehiclesDto();
            BeanUtils.copyProperties(pcVehicles, dto);
            dto.setIdImgList(pcVehicles.getIdImgs().split(","));
            dto.setVehiclePhotoList(pcVehicles.getVehiclePhoto().split(","));
            map.put("pcVehicles", dto);
            if (pcVehicles.getApplyType() == 0) {
                map.put("status", 2);
                map.put("statusName", "审核中");
            }
            if (pcVehicles.getApplyType() == 1) {
                map.put("status", 0);
                map.put("statusName", "申请通过");
            }
            if (pcVehicles.getApplyType() == 2) {
                map.put("status", 3);
                map.put("statusName", "申请失败");
                map.put("reason", pcVehicles.getReason());//申请失败原因
            }
            return R.success(map);
        }
        map.put("pcVehicles", null);
        map.put("status", 1);
        return R.success(map);
    }

    @Override
    public R updateVehicles(ApplyVehiclesDto applyVehiclesDto) {
        Long mid = getMid();
        QueryWrapper<PcVehicles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", mid);
        PcVehicles pcVehicles = pcVehiclesMapper.selectOne(queryWrapper);

        BeanUtils.copyProperties(applyVehiclesDto, pcVehicles);
        pcVehicles.setIdImgs(String.join(",", applyVehiclesDto.getIdImgList()));
        pcVehicles.setVehiclePhoto(String.join(",", applyVehiclesDto.getVehiclePhotoList()));
        pcVehicles.setApplyType(0);
        pcVehicles.setCreateUser(mid);
        pcVehicles.setCreateTime(new Date());
        int i = pcVehiclesMapper.updateById(pcVehicles);

        return i > 0 ? R.success() : R.fail("修改失败");

    }

    @Override
    public R<VehiclesServerRegionDto> findVehiclesServerRegion() {
        VehiclesServerRegionDto regionDto = new VehiclesServerRegionDto();
        Long mid = getMid();
        QueryWrapper<PcVehicles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", mid);
        PcVehicles pcVehicles = pcVehiclesMapper.selectOne(queryWrapper);
        if (pcVehicles != null) {
            BeanUtils.copyProperties(pcVehicles, regionDto);
            if (regionDto.getLongitude() != null && regionDto.getLatitude() != null) {
                JSONObject aMapByLngAndLat = GaoDeMapUtil.getAMapByLngAndLat(regionDto.getLongitude(), regionDto.getLatitude());
                regionDto.setAddress(aMapByLngAndLat.getString("formatted_address"));
            }
            if (pcVehicles.getIsOpenRadius() != null) {
                regionDto.setIsOpenRadius(pcVehicles.getIsOpenRadius() == 0);
            }
        }
        return R.success(regionDto);
    }

    @Override
    public R updateVehiclesServerRegion(VehiclesServerRegionDto regionDto) {
        Long mid = getMid();
        QueryWrapper<PcVehicles> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", mid);
        PcVehicles pcVehicles = pcVehiclesMapper.selectOne(queryWrapper);
        BeanUtils.copyProperties(regionDto, pcVehicles);
        pcVehicles.setIsOpenRadius(regionDto.getIsOpenRadius() ? 0 : 1);
        int i = pcVehiclesMapper.updateById(pcVehicles);
        return i > 0 ? R.success() : R.fail("修改失败");
    }

}
